<!--
 * @Description: 
 * @Author: wangchao
 * @Date: 2023-01-28 14:19:36
-->
<!--
 * @Description: 
 * @Author: wangchao
 * @Date: 2023-01-28 10:18:12
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>节流</title>
  </head>
  <body>
    <button id="btn">点击</button>
    <script>
      const btn = document.getElementById("btn");

      // isFetch 只能使用总函数，必须配置firstFunc
      function throttle(delay, firstFunc = null, isFetch = false) {
        let timer = null;
        return (v, secondFunc = null) => {
          return new Promise(resolve => {
            if (!timer) {
              timer = setTimeout(async () => {
                if (isFetch) {
                  let data = await firstFunc();
                  resolve(data);
                  timer = null;
                  return;
                }
                if (secondFunc) {
                  secondFunc(v);
                } else if (firstFunc) {
                  firstFunc(v);
                }
                timer = null;
              }, delay);
            }
          });
        };
      }

      let throttleFunc = throttle(
        1000,
        v => {
          // console.log("方式1: 通过传递总函数得到的" + v);
          return new Promise(resolve=>{
            setTimeout(() => {
              resolve('wow,通过fetch得到的')
            }, 2000);
          })
        },
        true
      );

      btn.addEventListener("click", e => {
        // 将函数回调权交给开发者
        // 方式1：
        // throttleFunc(333);
        // 方式2：
        // throttleFunc(333, val => {
        //   console.log("方式2: 通过传入内部函数得到的：" + val);
        // });
        // 方式3：
        throttleFunc().then(val => {
          console.log("方式3：通过promise回调得到的：" + val);
        });
      });
    </script>
  </body>
</html>
